连接数据库

您所在的位置:网站首页 数据库链接池 链接重置 连接数据库

连接数据库

2024-07-16 01:38:47| 来源: 网络整理| 查看: 265

GORM 官方支持的数据库类型有: MySQL, PostgreSQL, SQlite, SQL Server

MySQL import ( "gorm.io/driver/mysql" "gorm.io/gorm" ) func main() { // 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情 dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) }

注意:想要正确的处理 time.Time ,您需要带上 parseTime 参数, (更多参数) 要支持完整的 UTF-8 编码,您需要将 charset=utf8 更改为 charset=utf8mb4 查看 此文章 获取详情

MySQl 驱动程序提供了 一些高级配置 可以在初始化过程中使用,例如:

db, err := gorm.Open(mysql.New(mysql.Config{ DSN: "gorm:gorm@tcp(127.0.0.1:3306)/gorm?charset=utf8&parseTime=True&loc=Local", // DSN data source name DefaultStringSize: 256, // string 类型字段的默认长度 DisableDatetimePrecision: true, // 禁用 datetime 精度,MySQL 5.6 之前的数据库不支持 DontSupportRenameIndex: true, // 重命名索引时采用删除并新建的方式,MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引 DontSupportRenameColumn: true, // 用 `change` 重命名列,MySQL 8 之前的数据库和 MariaDB 不支持重命名列 SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置 }), &gorm.Config{}) 自定义驱动

GORM 允许通过 DriverName 选项自定义 MySQL 驱动,例如:

import ( _ "example.com/my_mysql_driver" "gorm.io/gorm" ) db, err := gorm.Open(mysql.New(mysql.Config{ DriverName: "my_mysql_driver", DSN: "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True&loc=Local", // Data Source Name,参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name }), &gorm.Config{}) 现有的数据库连接

GORM 允许通过一个现有的数据库连接来初始化 *gorm.DB

import ( "database/sql" "gorm.io/gorm" ) sqlDB, err := sql.Open("mysql", "mydb_dsn") gormDB, err := gorm.Open(mysql.New(mysql.Config{ Conn: sqlDB, }), &gorm.Config{}) PostgreSQL import ( "gorm.io/driver/postgres" "gorm.io/gorm" ) dsn := "user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai" db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

我们使用 pgx 作为 postgres 的 database/sql 驱动,默认情况下,它会启用 prepared statement 缓存,你可以这样禁用它:

// https://github.com/go-gorm/postgres db, err := gorm.Open(postgres.New(postgres.Config{ DSN: "user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai", PreferSimpleProtocol: true, // disables implicit prepared statement usage }), &gorm.Config{}) 自定义驱动

GORM 允许通过 DriverName 选项自定义 PostgreSQL 驱动,例如:

import ( _ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/postgres" "gorm.io/gorm" ) db, err := gorm.Open(postgres.New(postgres.Config{ DriverName: "cloudsqlpostgres", DSN: "host=project:region:instance user=postgres dbname=postgres password=password sslmode=disable", }) 现有的数据库连接

GORM 允许通过一个现有的数据库连接来初始化 *gorm.DB

import ( "database/sql" "gorm.io/gorm" ) sqlDB, err := sql.Open("postgres", "mydb_dsn") gormDB, err := gorm.Open(postgres.New(postgres.Config{ Conn: sqlDB, }), &gorm.Config{}) SQLite import ( "gorm.io/driver/sqlite" "gorm.io/gorm" ) // github.com/mattn/go-sqlite3 db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})

注意: 您也可以使用 file::memory:?cache=shared 替代文件路径。 这会告诉 SQLite 在系统内存中使用一个临时数据库。 (查看 SQLite 文档 获取详情)

SQL Server import ( "gorm.io/driver/sqlserver" "gorm.io/gorm" ) // github.com/denisenkom/go-mssqldb dsn := "sqlserver://gorm:LoremIpsum86@localhost:9930?database=gorm" db, err := gorm.Open(sqlserver.Open(dsn), &gorm.Config{}) ClickHouse package main import ( "gorm.io/driver/clickhouse" "gorm.io/gorm" ) type ExampleModel struct { ID uint `gorm:"column:id"` Name string `gorm:"column:name"` Age uint `gorm:"column:age"` } func main() { dsn := "clickhouse://username:password@host:port/database?dial_timeout=10s&read_timeout=20s" db, err := gorm.Open(clickhouse.Open(dsn), &gorm.Config{}) if err != nil { panic("failed to connect database") } // 创建数据表 if err := db.AutoMigrate(&ExampleModel{}); err != nil { log.Fatal(err) } // 写入数据 example := &ExampleModel{ID: 1, Name: "John Doe", Age: 25} if err := db.Create(example).Error; err != nil { log.Fatal(err) } // 查询单个数据 var result ExampleModel if err := db.First(&result, "id = ?", 1).Error; err != nil { log.Fatal(err) } fmt.Printf("ID: %d, Name: %s, Age: %d\n", result.ID, result.Name, result.Age) // 查询所有数据 var exas []ExampleModel db.Find(&exas, "age > ? ", 25) fmt.Println(exas) //批量保存 e1 := ExampleModel{ID: 4, Name: "name4", Age: 31} e2 := ExampleModel{ID: 5, Name: "name5", Age: 32} e3 := ExampleModel{ID: 6, Name: "name6", Age: 33} es := []ExampleModel{e1, e2, e3} db.Create(&es) } 连接池

GORM 使用 database/sql 维护连接池

sqlDB, err := db.DB() // SetMaxIdleConns 设置空闲连接池中连接的最大数量 sqlDB.SetMaxIdleConns(10) // SetMaxOpenConns 设置打开数据库连接的最大数量。 sqlDB.SetMaxOpenConns(100) // SetConnMaxLifetime 设置了连接可复用的最大时间。 sqlDB.SetConnMaxLifetime(time.Hour)

查看 通用接口 获取详情。

不支持的数据库

有些数据库可能兼容 mysql、postgres 的方言,在这种情况下,你可以直接使用这些数据库的方言。

对于其它不支持的数据,我们鼓励且欢迎大家伙开发更多数据库类型的驱动!

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接 我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/gorm/v2/connect...

译文地址:https://learnku.com/docs/gorm/v2/connect...



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭